package com.ruoyi.common.core.domain.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.yanx.common.utils.String_;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录用户身份权限
 *
 * @author gotanks
 */
@Data
public class LoginUser implements UserDetails {
    private static final long serialVersionUID = 1L;

    private String username;

    private String password;

    private Long userId;

    /**
     * 用户唯一标识
     */
    private String uuid;

    /**
     * 登录时间
     */
    private Long loginTime;

    /**
     * 过期时间
     */
    private Long expireTime;

    /**
     * 登录IP地址
     */
    private String ipaddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 浏览器类型
     */
    private String browser;

    /**
     * 操作系统
     */
    private String os;

    /**
     * 角色列表
     */
    private Set<String> roles;

    /**
     * 权限列表
     */
    private Set<String> permissions;

    /**
     * 变量
     */
    private Map<String, Object> user;


    private boolean accountNonExpired = true;

    private boolean accountNonLocked = true;

    private boolean credentialsNonExpired = true;

    private boolean enabled = true;

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<SimpleGrantedAuthority> authoritySet = new HashSet<>();
        if (roles != null) {
            Set<SimpleGrantedAuthority> roleSet = roles.stream().filter(String_::isNotBlank).map(t -> new SimpleGrantedAuthority("ROLE_" + t)).collect(Collectors.toSet());
            authoritySet.addAll(roleSet);
        }
        if (permissions != null) {
            Set<SimpleGrantedAuthority> permissionSet = permissions.stream().filter(String_::isNotBlank).map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
            authoritySet.addAll(permissionSet);
        }
        return authoritySet;
    }

    @JsonIgnore
    public void put(String key, Object value) {
        if (user == null) {
            user = new HashMap<>();
        }
        user.put(key, value);
    }

    @JsonIgnore
    public <T> T get(String key) {
        if (user == null) {
            return null;
        }
        Object value = user.get(key);
        return (T) value;
    }

}
